package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer server;

    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook address = addressBookMapper.getAddress(ordersSubmitDTO.getAddressBookId().intValue());
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        List<ShoppingCart> cartList = shoppingCartMapper.getCartList(BaseContext.getCurrentId());
        if (cartList == null || cartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(UUID.randomUUID().toString());
        order.setPhone(address.getPhone());
        order.setConsignee(address.getConsignee());
        order.setUserId(BaseContext.getCurrentId());
        orderMapper.addOrder(order);

        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderMapper.addOrderDetail(orderDetail);
        }
        shoppingCartMapper.cleanCart(BaseContext.getCurrentId());
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .id(order.getId()).build();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",order.getId());
        map.put("content","订单号："+order.getNumber());
        String string = JSON.toJSONString(map);
        server.sendToAllClient(string);
        return orderSubmitVO;
    }

    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> orders= orderMapper.getHistoryOrders(ordersPageQueryDTO);
        ArrayList<OrderVO> orderVOS = new ArrayList<>();

        if(orders.getTotal()>0&&orders!=null){
            for (Orders order : orders) {
                List<OrderDetail> list  =orderMapper.getOrderDetails(order.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                orderVO.setOrderDetailList(list);
                orderVOS.add(orderVO);
            }
        }

        return new PageResult(orders.getTotal(),orderVOS);
    }

    @Override
    public OrderVO getOrder(Long id) {
        Orders orders= orderMapper.getOrder(id);

        List<OrderDetail> list= orderMapper.getOrderDetails(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        Orders order = orderMapper.getOrder(id);
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.updateOrder(orders);
    }

    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderMapper.getOrderDetails(id);
        List<ShoppingCart> shoppingCartList=orderDetails.stream().map(o->{
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(o,cart);
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
            return cart;
        }).collect(Collectors.toList());

        for (ShoppingCart cart : shoppingCartList) {
            shoppingCartMapper.addCart(cart);
        }

    }

    @Override
    public PageResult getOrderList(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.getHistoryOrders(ordersPageQueryDTO);
       List<OrderVO> list= page.getResult().stream().map(o->{
           OrderVO orderVO = new OrderVO();
           BeanUtils.copyProperties(o,orderVO);
           return orderVO;
       }).collect(Collectors.toList());
        return new PageResult(page.getTotal(),list);
    }

    @Override
    public OrderStatisticsVO statistics() {

        Integer statusCount1 = orderMapper.getStatusCount(Orders.TO_BE_CONFIRMED);
        Integer statusCount2 = orderMapper.getStatusCount(Orders.CONFIRMED);
        Integer statusCount3 = orderMapper.getStatusCount(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO(statusCount1, statusCount2, statusCount3);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        orderMapper.updateOrder(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getOrder(id);
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",order.getId());
        map.put("content","订单号："+order.getNumber());
        String string = JSON.toJSONString(map);
        server.sendToAllClient(string);
    }
}




















